<template>
  <el-button @click="() => addView()">添加视图</el-button>
  <el-table
    :data="tableData"
    style="width: 100%; margin-bottom: 20px"
    row-key="view_authority_id"
    border
    default-expand-all
  >
    <el-table-column prop="view_authority_text" label="视图名称" />
    <el-table-column prop="view_level" label="层级" sortable />
    <el-table-column prop="view_name" label="视图CODE" sortable />
    <el-table-column label="操作" width="260">
      <template #default="scope">
        <el-button
          type="primary"
          size="small"
          @click="addView(scope.row.view_authority_id, scope.row.view_authority_text)"
          >添加子视图</el-button
        >
        <el-button
          type="primary"
          size="small"
          @click="editView(scope.row.view_authority_id, scope.row.view_authority_pid)"
          >编辑视图</el-button
        >
        <el-popconfirm
          width="220"
          cancel-button-text="取消"
          confirm-button-text="确定"
          icon-color="#626AEF"
          @confirm="doDelete(scope.row.view_authority_id)"
          title="确定要删除此视图吗？"
        >
          <template #reference>
            <el-button type="danger" size="small">删除</el-button>
          </template>
        </el-popconfirm>
      </template>
    </el-table-column>
  </el-table>
  <ViewForm v-if="showViewForm" :pid="pid" :id="curId" :ptext="ptext" @close="closeDialog" />
</template>

<script setup lang="ts">
import { GET_VIEW_LIST, DELETE_VIEW } from '@/api/view'
import getTreeData from '@/utils/arrayToTree'
import ViewForm from './components/ViewForm.vue'
import { ref } from 'vue'
const tableData = ref([])
const getData = async () => {
  const res = await GET_VIEW_LIST()
  tableData.value = getTreeData(
    res.data,
    'view_authority_id',
    'view_authority_pid',
    'children',
    null
  )
}
const pid = ref()
const curId = ref()
const ptext = ref()
const showViewForm = ref(false)
const addView = (id?: string, text?: string) => {
  console.log(id)
  curId.value = ''
  if (id) {
    pid.value = id
    ptext.value = text
  } else {
    pid.value = null
  }
  showViewForm.value = true
}
const editView = (id: string, parentId: string) => {
  curId.value = id
  if (parentId) {
    pid.value = parentId
  } else {
    pid.value = null
  }
  showViewForm.value = true
}
const closeDialog = (flag?: boolean) => {
  showViewForm.value = false
  if (flag) {
    getData()
  }
}
const doDelete = (id: string) => {
  DELETE_VIEW(id).then(() => {
    getData()
  })
}

getData()
</script>

<style></style>
